
package com.scalar.chiptrack.utils;

import java.io.*;
import java.net.URL;

import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.Constants;
import org.apache.poi.util.StringUtil;


/**
 * Contains utility method for working with the files
 *
 * @author  Rohan
 * @version  1.0
 */
public class FileUtils
{
    // Convert File to URL
    public static URL fileToURL(File file)
    {
       String path = file.getAbsolutePath();
       String fSep = System.getProperty( "file.separator" );

		if (fSep != null && fSep.length() == 1)
       	{
       		path = path.replace(fSep.charAt(0), '/');
		}
       	if (path.length() > 0 && path.charAt(0) != '/')
       	{
       		path = '/' + path;
		}

       	try
       	{
       		return new URL("file", null, path);
		}
		catch (java.net.MalformedURLException e)
       	{
       		throw new Error("unexpected MalformedURLException");
       	}
    }


    /**
     * Returns the extension of the file given by this file name
     *
     * @param fileName
     * @throws ScalarException
     */
    public static String getFileExtension( String fileName ) throws ScalarException
    {
        String extension = "";
        int index = fileName.lastIndexOf( "." );
        if( index != -1 )
        {
            extension = fileName.substring( index + 1, fileName.length() );
        }

        return extension;
    }

    /**
     * Returns the file name with out the extension
     *
     * @param fileName
     * @throws ScalarException
     */
    public static String getFileNameWithoutExtension( String fileName ) throws ScalarException
    {
        String extension = fileName;
        int index = fileName.lastIndexOf( "." );
        if( index != -1 )
        {
            extension = fileName.substring( 0, index );
        }
        return extension;
    }

    /**
     * Returns if the file name has an extension
     *
     * @param fileName
     * @return
     * @throws ScalarException
     */
    public static boolean hasExtension( String fileName ) throws ScalarException
    {
        boolean hasExtension = false;
        if( fileName.indexOf( "." ) != -1 )
        {
            hasExtension = true;
        }
        return hasExtension;
    }

    /**
     * Reads data from the given file location and returns it as a String
     *
     * @param absFileName to read from
     */
    public static String readFile( String absFileName ) throws Exception
    {
        StringBuffer buf = null;
        BufferedReader bReader = null;

        try
        {
            bReader = new BufferedReader( new FileReader( absFileName ) );

            String line = null;
            buf = new StringBuffer();

            while( ( line = bReader.readLine() ) != null )
            {
                buf.append( line ).append( Constants.LINE_SEPARATOR );
            }
        }
        catch( Throwable t )
        {

        }
        finally
        {
            if( bReader != null )
            {
                bReader.close();
            }
        }

        return buf.toString();
    }

    public static String readFileAsString( String absFileName ) throws Exception
    {
        return null;
    }


	public static void saveFile( byte[] inputData, String absFileName ) throws Exception
	{
		if( ( inputData == null ) || ( inputData.length == 0 ) || ( absFileName == null ) )
		{
			return;
		}

		FileOutputStream fos = null;
		try
		{
			fos = new FileOutputStream( absFileName, false );
			fos.write( inputData );
		}
		catch( Throwable t )
		{
			t.printStackTrace();
		}
		finally
		{
			if( fos != null )
			{
				try{ fos.close(); fos = null; } catch( Throwable t ) {}
			}
		}

	}

    /**
     *
     * @param filename
     * @param directoryPath
     * @param inputStream
     * @return the path to the file
     * @throws Exception
     */
    public static String saveFile(String filename, String directoryPath, InputStream inputStream) throws Exception {
        OutputStream out = null;
        String msg = null;
        File tempDir = new File(directoryPath);
        try{
        tempDir.mkdirs();
        out = new BufferedOutputStream(
                new FileOutputStream(tempDir + File.separator + filename));
        byte[] buffer = new byte[8*1024];
        int numRead;
        while ((numRead = inputStream.read(buffer)) != -1) {
            out.write(buffer, 0, numRead);
        }
        } finally{
            if(out != null) {
                out.close();
            }
        }

        msg = tempDir + File.separator + filename;
        return msg;
    }

    public static void copyDir(String fromDirPath, String toDirPath) throws Exception {
        File fromDir = new File(fromDirPath);
        if (fromDir.isDirectory() && fromDir.exists()) {
            File[] files = fromDir.listFiles();
            for (File file : files) {
                FileInputStream fileInputStream = new FileInputStream(file);
                saveFile(file.getName(), toDirPath, fileInputStream);
                fileInputStream.close();
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }

    /**
     * replaces the characters which are not allowed( \ / : * ? " &lt; &gt; | ) in filname with "_".
     * @param fileName to be normalized
     * @return the valid filename.
     * <br> Eg: fileName = sujan\/:*?"&lt;&gt;|.png
     * <br> returns: sujan_________.png
     */
    public static String normalizeFileName(String fileName){
        if(StringUtils.isNullOrEmpty(fileName)){
            return fileName;
        }
        return fileName.replaceAll("[\\\\/:\\*\\?\"<>|]", "_");
    }
}
